package com.esun.ui;

import org.androidpn.client.Constants;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.widget.TextView;
import android.widget.Toast;

import com.esun.RabbitApplication;
import com.esun.config.Config;
import com.esun.config.DistributionChannels;
import com.esun.config.Key;
import com.esun.model.LoadingInfo;
import com.esun.model.UserInfo;
import com.esun.rabbit2.communicaters.NewLoadingCommunicater;
import com.esun.rabbit2.viewer.MainAct;
import com.esun.rabbit2.viewer.NewFunctionIntroductionAct;
import com.esun.util.log.EDebug;
import com.esun.util.magic.magic;

/**
 * @Title: Splash.java
 * @Package com.esun.ui
 * @Description: (启动画面Activity)
 * @author City jiangsy@500wan.com
 * @date 2011-5-13 下午05:17:18 copy right 深圳市易讯天空网络技术有限公司
 */
public class Splash extends Activity {
	/** Called when the activity is first created. */
	private Intent intent = new Intent();
	private final int SPLASH_IS_ERROR = 1002;
	/** 登陆成功 */
	private final int LOGIN_SUCCEED = 1003;
	/** 登陆失败 */
	private final int LOGIN_FIALED = 1004;
	/** 登陆锁定 */
	private final int LOGIN_LOCKED = 1005;

	// DataBase 信息
	private static final String TABLENAME = "users";

	// 声明db对象
	private SQLiteDatabase db;

	// 数据表创建语句
	private static final String CREAT_TABLE = "CREATE TABLE users (_id INTEGER PRIMARY KEY,name TEXT,password TEXT,save TEXT,autologin TEXT)";

	// 数据表 各列 名称定义
	private static final String ID = "_id";

	// add by billy 11-11-07
	// DataBase 信息
	// private static final String TABLENAME_LOCAL = "localconfig";

	// 声明db对象
	private SQLiteDatabase db_local;

	// 数据表创建语句
	private static final String CREAT_TABLE_LOCAL = "CREATE TABLE localconfig (_id INTEGER PRIMARY KEY,accountprotect TEXT,currentversion TEXT)";

	// 数据表 各列 名称定义
	private static final String ID_LOCAL = "_id";
	// private static final String CURRENT_VERSION = "currentversion";

	private NewLoadingCommunicater newLoadingCommunicater;
	private Handler handler;
	private TextView tvVersion;
	private LoadingInfo loadingInfo;

	/**
	 * @Fields channel : 渠道号
	 */
	private String channel = "";
	/**
	 * @Fields verson : 版本号
	 */
	private String version = "";

	private long splashStart;
	private long splashEnd;
	private long communicaterStart;
	private long communicaterEnd;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		splashStart = System.currentTimeMillis();
		EDebug.o(this, "Splash 开始时间" + splashStart);
		// 锁定横屏
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		setContentView(R.layout.splash);
		UserInfo.getUserInfo().setBuyingRecharge(false);
		initUI();
		initHandler();
		dataPrepare();
		((RabbitApplication) getApplication()).startPushService();

	}

	private void initUI() {
		tvVersion = (TextView) findViewById(R.id.splash_tv_version);
		tvVersion.setText("V" + getResources().getString(R.string.version) + "版本");
	}

	/**
	 * @Title: initHandler
	 * @Description: 初始化handler
	 * @param: 设定文件
	 * @return: void 返回类型
	 * @throws
	 */
	private void initHandler() {
		handler = new Handler() {

			@Override
			public void handleMessage(Message msg) {

				super.handleMessage(msg);

				switch (msg.what) {

				case LOGIN_SUCCEED:
					EDebug.o(Splash.this, "登陆成功");
					newLoadingCommunicater.updateInfo();
					loadingInfo = LoadingInfo.getInstance();
					UserInfo.getUserInfo().setResetInputPasswordTime();
					UserInfo.getUserInfo().setNetWork(true);
					UserInfo.getUserInfo().setUserBalance(loadingInfo.getMoney());
					UserInfo.getUserInfo().setUserFreeze(loadingInfo.getFreezemoney());
					UserInfo.getUserInfo().setUserSession(loadingInfo.getCk());
					Toast.makeText(Splash.this, UserInfo.getUserInfo().getUserName() + ",您已登录成功", Toast.LENGTH_SHORT).show();
					break;

				case LOGIN_FIALED:
					EDebug.o(Splash.this, "登陆失败");
					newLoadingCommunicater.updateInfo();
					break;

				case LOGIN_LOCKED:
					EDebug.o(Splash.this, "登陆锁定");
					newLoadingCommunicater.updateInfo();
					break;

				case Config.CONNECTION_FAIL:
					EDebug.o(Splash.this, "登陆异常");
					break;

				default:

					break;

				}
				if (isFirstRunApp()) {
					EDebug.o(Splash.this, "首次启动");
					intent.setClass(Splash.this, NewFunctionIntroductionAct.class);
				} else {
					EDebug.o(Splash.this, "非首次启动");
					intent.setClass(Splash.this, MainAct.class);
				}
				startActivity(intent);
				Splash.this.finish();
				splashEnd = System.currentTimeMillis();
				EDebug.o(this, "Splash结束时间" + splashEnd);
				EDebug.o(this, "Splash 总体耗时" + (splashEnd - splashStart));
			}

		};
	}

	/**
	 * @Title: dataPrepare
	 * @Description: 通信数据准备
	 * @param: 设定文件
	 * @return: void 返回类型
	 * @throws
	 */
	private void dataPrepare() {
		// 获取本地数据库保存信息
		getDBInfo();
		getDBLocalInfo();
		channel = DistributionChannels.QUDAO;
		try {
			version = this.getPackageManager().getPackageInfo(Config.APP_PACKAGE_INFO, 0).versionName;
		} catch (NameNotFoundException e) {
			version = Config.NUM0;
		}
		loadingThread();

	}

	private void loadingThread() {
		new Thread() {

			@Override
			public void run() {
				if (newLoadingCommunicater == null) {
					newLoadingCommunicater = new NewLoadingCommunicater();
				}
				String userName;
				String userPwd;
				String userIMEI;
				if (UserInfo.getUserInfo().isAutoLogin()) {
					userName = UserInfo.getUserInfo().getUserName();
					userPwd = UserInfo.getUserInfo().getUserPwd();
				} else {
					EDebug.o(this, "不自动登陆 所以用户名传空");
					userName = Config.NULLMARK;
					userPwd = Config.NULLMARK;
				}

				SharedPreferences sharedPre = Splash.this.getSharedPreferences(Config.CLIENT_PREFERENCES, Context.MODE_PRIVATE);
				userIMEI = sharedPre.getString(Constants.DEVICE_ID, Config.DEFAULT_LEAGUAGE_NUM);

				try {
					communicaterStart = System.currentTimeMillis();
					EDebug.o(this, "loading接口开始通讯时间" + communicaterStart);
					String useragent = android.os.Build.MODEL;
					String IMEI = magic.getIMEI(Splash.this);
					boolean isSucceed = newLoadingCommunicater.isCommunicatedSucceed(userName, userPwd, channel, version, userIMEI, useragent, IMEI);
					if (isSucceed) {
						Message msg = handler.obtainMessage(LOGIN_SUCCEED, null);
						handler.sendMessage(msg);
					} else {
						if (newLoadingCommunicater.getState() == 109) {
							Message msg = handler.obtainMessage(LOGIN_FIALED, null);
							handler.sendMessage(msg);
						} else if (newLoadingCommunicater.getState() == 220) {
							Message msg = handler.obtainMessage(LOGIN_LOCKED, null);
							handler.sendMessage(msg);
						} else {
							Message msg = handler.obtainMessage(SPLASH_IS_ERROR, null);
							handler.sendMessage(msg);
						}
					}
				} catch (Exception e) {
					Message msg = handler.obtainMessage(Config.CONNECTION_FAIL, null);
					handler.sendMessage(msg);
				}
				communicaterEnd = System.currentTimeMillis();
				EDebug.o(this, "loading接口结束通讯时间" + communicaterEnd);
				EDebug.o(this, "loading 接口总体耗时" + (communicaterEnd - communicaterStart));
			}
		}.start();
	}

	/**
	 * @Title: getDBInfo
	 * @Description: 获取用户登录信息 用户名 密码 是否保存信息 是否自动登录
	 * @param: 设定文件
	 * @return: void 返回类型
	 * @throws
	 */
	private void getDBInfo() {
		// 创建数据库表信息
		db = Splash.this.openOrCreateDatabase(Key.KEY_DB_ARABBIT2, MODE_PRIVATE, null);
		if (!(isTableExits(db, TABLENAME))) {
			EDebug.o(this, "创建表users");
			db.execSQL(CREAT_TABLE);
			ContentValues cv = new ContentValues();
			cv.put(Key.KEY_NAME, Config.NULLMARK);
			cv.put(Key.KEY_PASSWORD, Config.NULLMARK);
			cv.put(Key.KEY_SAVE, Config.NUM0);
			cv.put(Key.KEY_AUTOLOGIN, Config.NUM0);
			db.insert(Key.KEY_USERS, null, cv);
		} else {
			// 判断是否穿在autologin字段
			Cursor cur = db.rawQuery("SELECT * FROM users", null);
			if (cur != null) {
				boolean isExit = false;
				for (int i = 0; i < cur.getCount(); i++) {
					int numColumn = cur.getColumnIndex(Key.KEY_AUTOLOGIN);
					EDebug.o("第一次查询" + cur.getCount() + "autologin columnindex  = " + numColumn);
					if (numColumn > 0) {
						isExit = true;
						EDebug.o(this, "auto login is exit, state = " + isExit);
						break;
					}
				}
				// 没有的话插入autologin字段，并赋默认值
				if (!isExit) {
					EDebug.o(this, "插入antologin字段");
					String addAutologinColumn = "alter table users add autologin TEXT";
					db.execSQL(addAutologinColumn);
					ContentValues cv = new ContentValues();
					cv.put(Key.KEY_AUTOLOGIN, Config.NUM0);
					db.update(TABLENAME, cv, "_id=?", new String[] { Config.NUM1 });
				}
			}
		}
		// 获取数据库内保存的信息
		Cursor cur;
		cur = db.query(TABLENAME, new String[] { Key.KEY_NAME, Key.KEY_PASSWORD, Key.KEY_SAVE, Key.KEY_AUTOLOGIN, ID }, null, null, null, null, null);
		String tempSave;
		String tempName;
		String tempPwd;
		String tempAutoLogin;
		cur.moveToFirst();

		tempName = cur.getString(0);
		tempPwd = cur.getString(1);
		tempSave = cur.getString(2);
		tempAutoLogin = cur.getString(3);
		EDebug.o("print by billy =>> user name = " + tempName);
		EDebug.o("print by billy =>> user pwd  = " + tempPwd);
		EDebug.o("print by billy =>> is save   = " + tempSave);
		EDebug.o("print by billy =>> is autologin   = " + tempAutoLogin);

		UserInfo.getUserInfo().setUserName(tempName);
		// 不保存登陆信息
		if (tempSave.equals(Config.NUM0)) {
			UserInfo.getUserInfo().setUserPwd(Config.NULLMARK);
			UserInfo.getUserInfo().setSaveData(false);
			UserInfo.getUserInfo().setAutoLogin(false);
		} else {
			// 保存登陆信息
			UserInfo.getUserInfo().setUserPwd(tempPwd);
			UserInfo.getUserInfo().setSaveData(true);
			// 不自动登陆
			if (tempAutoLogin.equals(Config.NUM0)) {
				UserInfo.getUserInfo().setAutoLogin(false);
			} else {
				// 自动登录
				UserInfo.getUserInfo().setAutoLogin(true);
			}
		}
		// 关闭游标
		if (cur != null) {
			try {
				cur.close();
			} catch (Exception e) {
				// TODO: handle exception
			}
		}
		// 关闭数据库
		db.close();
	}

	/**
	 * @Title: getDBLocalInfo
	 * @Description: 获取本地配置信息 当前版本号 以及 账号保护状态
	 * @param: 设定文件
	 * @return: void 返回类型
	 * @throws
	 */
	private void getDBLocalInfo() {
		// 创建数据库表信息
		db_local = Splash.this.openOrCreateDatabase(Key.KEY_DB_ARABBIT2_LOCALCONFIG, MODE_PRIVATE, null);
		if (!(isTableExits(db_local, Key.KEY_LOCALCONFIG))) {
			EDebug.o(this, "创建表localconfig");
			db_local.execSQL(CREAT_TABLE_LOCAL);
			ContentValues cv = new ContentValues();
			cv.put(Key.KEY_ACCOUNTPROTECT, Config.NULLMARK);
			cv.put(Key.KEY_CURRENTVERSION, Config.NULLMARK);
			db_local.insert(Key.KEY_LOCALCONFIG, null, cv);
		}
		// 获取数据库内保存的信息
		Cursor cur;
		cur = db_local.query(Key.KEY_LOCALCONFIG, new String[] { Key.KEY_ACCOUNTPROTECT, Key.KEY_CURRENTVERSION, ID_LOCAL }, null, null, null, null, null);

		String tempAccountState = "";
		String tempCurrentVersion = "";

		cur.moveToFirst();

		tempAccountState = cur.getString(0);
		tempCurrentVersion = cur.getString(1);
		EDebug.o(this, "database account protect state = " + tempAccountState);
		EDebug.o(this, "database current version = " + tempCurrentVersion);
		// 判断是否开启账号自动保护功能
		if (tempAccountState.equals(Config.NULLMARK) || tempAccountState.equals(Config.NUM1)) {
			UserInfo.getUserInfo().setAccountProtectState(true);
			EDebug.o(this, "user account protect state == true");
		} else if (tempAccountState.equals(Config.NUM0)) {
			UserInfo.getUserInfo().setAccountProtectState(false);
			EDebug.o(this, "user account protect state == false");
		}
		UserInfo.getUserInfo().setCurrentVersion(tempCurrentVersion);
		// 关闭游标
		if (cur != null) {
			try {
				cur.close();
			} catch (Exception e) {
				// TODO: handle exception
			}
		}
		// 关闭数据库
		db_local.close();

	}

	/**
	 * @Title: isTableExits
	 * @Description: 查询数据库中 该表是否存在
	 * @param: @param db
	 * @param: @param tablename
	 * @param: @return 设定文件
	 * @return: boolean 返回类型
	 * @throws
	 */
	private boolean isTableExits(SQLiteDatabase db, String tablename) {
		boolean result = false;// 表示不存在
		String str = "SELECT COUNT(*) FROM sqlite_master where type='table' and name='" + tablename + "'";
		Cursor c = db.rawQuery(str, null);
		c.moveToFirst();
		int xcount = Integer.parseInt(c.getString(0));
		if (xcount != 0) {
			result = true; // 表存在
			EDebug.o(this, tablename + "表存在");
		} else {
			EDebug.o(this, tablename + "表不存在");
		}
		return result;
	}

	/**
	 * @Title isFirstRunApp
	 * @Description 是否第一次运行该版本的客户端
	 * @return boolean 是否首次启动客户端
	 * */
	private boolean isFirstRunApp() {

		try {

			String local_version = Splash.this.getPackageManager().getPackageInfo(Config.APP_PACKAGE_INFO, 0).versionName;

			if (UserInfo.getUserInfo().getCurrentVersion().equals(local_version)) {
				EDebug.o(this, "同版本，不需要显示");
				return false;
			} else {
				EDebug.o(this, "不同版本，需要显示,并更新数据库");
				updataDBVersion(local_version);
				UserInfo.getUserInfo().setCurrentVersion(local_version);
				return true;
			}
		} catch (NameNotFoundException e) {
			EDebug.o(this, "异常");
			return false;
		}
	}

	/**
	 * @Title updataDBVersion
	 * @Description 将新版的客户端版本号写入数据库
	 * @param str
	 *            版本号
	 * @return void 返回类型
	 * */
	private void updataDBVersion(String str) {
		db_local = Splash.this.openOrCreateDatabase(Key.KEY_DB_ARABBIT2_LOCALCONFIG, MODE_PRIVATE, null);
		ContentValues cv = new ContentValues();
		cv.put(Key.KEY_CURRENTVERSION, str);

		db_local.update(Key.KEY_LOCALCONFIG, cv, "_id=?", new String[] { Config.NUM1 });
		db_local.close();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		return super.onKeyDown(keyCode, event);
	}

}
